<!--
 * @Author: wangze@linkstec.com
 * @Date: 2022-01-26 14:15:39
 * @Function: Please Input Function
-->
<template>
  <lk-dialog
    :visible="visible"
    width="1200px"
    @close="closeAction"
    @opened="opened">
    <template slot="title">
      <div class="title-item">
        <span class="title-text" style="font-size: 18px;margin-right:10px;">产品材料和协议须知</span>
        <span class="item-text" style="font-size: 18px;">{{ prodName }}</span>
      </div>
    </template>
    <template slot="footer" v-if="type!='SplitOrder'">
      <div class="confirm-footer">
        <div class="confirm-text-wrap">
          阅读并同意本页面内条款，代表本人已同意所管理的交易账号全部须知相关协议。
        </div>
        <template v-if="confirmChecked">
          <el-button key="back" size="small" plain @click="closeAction">关闭</el-button>
        </template>
        <template v-else>
          <el-button key="back" size="small" plain @click="closeAction">放弃并返回</el-button>
          <el-button key="submit" size="small" type="primary" :disabled="countDownTime > 0" @click="okAction">同意签署<span v-if="countDownTime > 0">({{ countDownTime }}s)</span></el-button>
        </template>
      </div>
    </template>
    <template slot="footer" v-if="type=='SplitOrder'">
      <div class="confirm-footer">
        <div class="confirm-text-wrap">

        </div>
        <template>
          <el-button key="back" size="small" plain @click="closeAction">关闭</el-button>
        </template>
      </div>
    </template>
    <div class="body-container">
      <div class="left-menu">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          background-color="#F6F6F6"
          mode="vertical"
          @select="handleSelect">
          <el-menu-item
            :index="contractI"
            :key="contractI"
            v-for="(contract,contractI) in contractList"
            style="overflow:hidden;white-space: nowrap;text-overflow: ellipsis;"
            :title="contract.abstractName">
            <span>{{ contract.abstractName }}</span>
          </el-menu-item>
        </el-menu>
      </div>
      <div class="right-content" id="pdfContent">
        <pdf
          ref="pdfRef"
          @page-loaded="loaded"
          v-for="i in numPages"
          :key="i"
          :src="currentPdfSrc"
          :page="i"
        ></pdf>
        <el-tooltip effect="dark" content="点击下载" placement="bottom">
          <el-button
            v-if="downloadShow"
            class="down-btn"
            icon="el-icon-download"
            plain
            type="primary"
            size="mini"
            @click="previewPdf"></el-button>
        </el-tooltip>
      </div>
    </div>
  </lk-dialog>
</template>

<script>
import pdf from 'vue-pdf';
import { loading } from '@/utils';

export default {
  name: 'ConfirmBeforeBuy',
  components: {
    pdf
  },
  props: {
    confirmChecked: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    productType: {
      type: String,
      default: ''
    }
  },
  // 定义属性
  data () {
    return {
      visible: false,

      prodCode: null,
      prodName: null,
      typeCode: null,
      serialId: '', // 签署后的流水号

      activeIndex: 0,
      contractList: [], // 合同列表
      currentPdfSrc: '',

      page: 1,
			numPages: undefined,

      countDownTime: 5,
      timer: null,
      formData: {},
      downloadUrl: '',
      downloadShow: false
    };
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 供外部调用
    show ({ prodCode, prodName, typeCode }) {
      this.visible = true;

      this.prodCode = prodCode;
      this.prodName = prodName;
      this.typeCode = typeCode;
    },
    showSplitOrder (formData) {
      this.visible = true;
      this.formData = formData;
    },
    // 关闭操作
    closeAction () {
      this.visible = false;
      this.resetData();
    },
    // 确认操作 - 合同签署
    okAction () {
      this.$api.publicFund.signContract({
        CONTRACT_LIST: this.contractList.map(item => {
          return {
            proCode: item.proCode,
            proName: item.proName,
            productType: this.productType,
            contractNo: item.contractNo,
            contractName: item.contractName,
            contractUrl: item.contractUrl
          };
        })
      }).then(res => {
        const data = res.data || {};
        this.$emit('ok', {
          serialId: data.serialId,
          prodCode: data.proCode,
          prodName: this.prodName,
          typeCode: this.typeCode
        });
        this.visible = false;
        this.resetData();
      });
    },
    // 重置数据
    resetData () {
      this.prodCode = null;
      this.prodName = null;
      this.typeCode = null;
      this.serialId = ''; // 签署后的流水号

      this.contractList = [];
      this.currentPdfSrc = '';
      this.activeIndex = 0;

      this.page = 1;
			this.numPages = undefined;

      this.countDownTime = 5;
      clearInterval(this.timer);
      this.timer = null;
    },

    // 创建定时器
    createTimer () {
      this.timer = setInterval(() => {
        this.countDownTime--;
        if (this.countDownTime === 0) {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },

    // 协议合同切换
    handleSelect (key, keyPath) {
      document.getElementById('pdfContent').scrollTop = 0;
      this.activeIndex = key;
      this.page = 1;
      this.getNumPages(this.contractList[this.activeIndex].contractUrl);
    },

    // 弹窗弹出后
    opened () {
      this.queryContract();
    },

    // 查询合同
    queryContract () {
      if (this.type !== 'SplitOrder') {
        this.$api.publicFund.getContract({
          PRO_CODE: this.prodCode,
          PRO_NAME: this.prodName
        }).then(res => {
          const data = res.data || [];
          this.contractList = data;
          this.getNumPages(this.contractList[0].contractUrl);
        });
      } else {
        this.$api.publicFund.getSplitContract(this.formData).then(res => {
          const data = res.data || [];
          this.contractList = [data];
          this.getNumPages(this.contractList[0].contractUrl);
        });
      }
    },

    // 加载完
    loaded (pageIndex) {
      if (pageIndex === this.numPages) {
        loading(false);
        if (!this.timer) {
          this.createTimer();
        }
      }
    },
    getNumPages (url) {
      loading(true);
      this.downloadUrl = url;
      this.downloadShow = false;
      if (document.location.protocol.includes('https') && !url.includes('https')) {
        url = url.replace('http', 'https');
      }
      this.currentPdfSrc = pdf.createLoadingTask(url);
      this.currentPdfSrc.promise.then(pdf => {
        this.numPages = pdf.numPages;
        this.downloadShow = true;
      }).catch(() => {
        console.error('加载失败');
        loading(false);
      });
    },
    previewPdf () {
      window.open(this.downloadUrl);
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang='scss' scoped>
.body-container{
  display: flex;
  height: 500px;
  position: relative;
  .left-menu{
    width: 160px;
    min-width: 160px;
    background-color: #f6f6f6;
    ::v-deep .el-menu{
      border-right: 0;
    }
    ::v-deep .is-active{
      background-color: #ffffff !important;
    }
  }
  .right-content{
    flex: 1;
    width: 0;
    overflow-y: auto;
    overflow-x: hidden;
    .down-btn{
      position: absolute;
      top: 15px;
      right: 35px;
      z-index: 10;
      font-size: 18px;
    }
  }
}
.confirm-footer{
  display: flex;
  align-items: center;
  .confirm-text-wrap{
    flex: 1;
    width: 0;
    font-size: 16px;
    color: #999999;
    font-weight: 400;
    word-break: break-all;
    text-align: left;
  }
}

</style>
